package models

import "github.com/astaxie/beego/orm"

func init() {
	orm.RegisterModel(new(Config))
}

type Config struct {
	Id    int    `json:"id"`
	Key   string `json:"key" orm:"size(128);unique"`
	Value string `orm:"size(128)" json:"value"`
	Desc  string `orm:"size(128)"` // 描述
}

func (o *Config) TableName() string {
	return "global_configs"
}

func (o *Config) Save() error {
	var err error
	if o.Id == 0 {
		_, err = orm.NewOrm().Insert(o)
	} else {
		_, err = orm.NewOrm().Update(o)
	}
	return err
}

func CreateConfig(key, value, desc string) error {
	config := Config{
		Key:   key,
		Value: value,
		Desc:  desc,
	}
	_, err := orm.NewOrm().Insert(&config)
	return err
}

func GetOneConfig(key string) (value string, err error) {
	c := Config{}
	err = orm.NewOrm().QueryTable(new(Config)).Filter("key", key).One(&c)
	return c.Value, err
}

func GetConfigObjFromKey(key string) (*Config, error) {
	var err error
	c := Config{}
	err = orm.NewOrm().QueryTable(new(Config)).Filter("key", key).One(&c)
	return &c, err
}

func GetConfigFromId(id int) (*Config, error) {
	config := Config{Id: id}
	err := orm.NewOrm().Read(&config)
	return &config, err
}

func GetConfigsPaginator(limit, page int) (configs []Config, total int64, err error) {
	querySet := orm.NewOrm().QueryTable(new(Config))
	total, _ = querySet.Count()
	_, err = querySet.Offset((page - 1) * limit).Limit(limit).All(&configs)
	return
}

func GetAllConfigs() (configs map[string]string, err error) {
	var config []Config
	_, err = orm.NewOrm().QueryTable(new(Config)).All(&config)
	if err != nil {
		return
	}
	configs = make(map[string]string)
	for _, c := range config {
		configs[c.Key] = c.Value
	}
	return
}
